/**
 * 给定一个二叉树，判断它是否是高度平衡的二叉树。
 * <p>
 * 本题中，一棵高度平衡二叉树定义为：
 * <p>
 * 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
 */
class Solution {

    public static void main(String[] args) {
        /*TreeNode root = new TreeNode(1);
        TreeNode node21 = new TreeNode(2);
        TreeNode node22 = new TreeNode(2);
        TreeNode node31 = new TreeNode(3);
        TreeNode node32 = new TreeNode(3);
        TreeNode node42 = new TreeNode(4);
        root.left = node21;
        root.right = node22;
        node21.right = node31;
        node22.left = node32;
        node22.right = node42;*/
        TreeNode root = new TreeNode(1);
        TreeNode node21 = new TreeNode(2);
        TreeNode node22 = new TreeNode(2);
        TreeNode node31 = new TreeNode(3);
        TreeNode node32 = new TreeNode(3);
        TreeNode node41 = new TreeNode(4);
        TreeNode node42 = new TreeNode(4);
        root.left = node21;
        root.right = node22;
        node21.left = node31;
        node21.right = node32;
        node31.left = node41;
        node31.right = node42;
        System.out.println(isBalanced(root));
    }

    private static boolean flag;

    public static boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        flag = true;
        int left = deep(root.left);
        if (!flag) {
            return flag;
        }
        int right = deep(root.right);
        if (!flag) {
            return flag;
        }
        int x = left - right;
        return x <= 1 && x >= -1;
    }

    public static int deep(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = deep(root.left);
        if (!flag) {
            return 0;
        }
        int right = deep(root.right);
        if (!flag) {
            return 0;
        }
        int x = left - right;
        if (x > 1 || x < -1) {
            flag = false;
        }
        return Math.max(left + 1, right + 1);
    }
}


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}